import subprocess
import json
import daemon
import redis
import psycopg2
from rocketmq.client import Producer, Message
import requests
import paramiko
import os


def local_2_remote(ssh_args,local_file,remote_dir):
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(*ssh_args)
    # 创建SFTP客户端
    sftp = client.open_sftp()
    # 上传文件到远程目录
    sftp.put(local_file, remote_dir + "/" + local_file.split('/')[-1])
    # 关闭SFTP和SSH客户端
    sftp.close()
    client.close()
    return


def name_2_info(cargs,name):
    connection = psycopg2.connect(**cargs)
    connection.autocommit = True
    cursor = connection.cursor()
    query = f"""select tile,product_date,cloud,tif_path,ST_AsText(geom)
        from sentinel2_l1c
        where name = '{name}';
        """
    cursor.execute(query)
    data = cursor.fetchone()
    cursor.close()
    connection.close()
    return data


# 发送数据到消息队列
def send_data(ssh_args,cargs,json_dir,zip_path,topic="henan_rsanalysis_s2_1c_collect",addr='192.168.1.70:9876'):
    name = os.path.basename(zip_path).replace(".zip","")
    row = name_2_info(cargs,name)
    producer = Producer("data")
    producer.set_namesrv_addr(addr)
    producer.start()
    data = {
        "tile": row[0],  # 假设其他属性字段在结果中的索引为1
        "product_date": row[1].strftime("%Y-%m-%d"),
        "cpjbdm": "1",
        "cpjdmc": "L1C",
        "imgtype_code": "S2",
        "imgtype_name": "Sentinel-2",
        "cloud": float(row[2]),
        "tif_path": row[3],
        "geometry": row[4]}
    json_path = os.path.join(json_dir,f"{name}.json")
    local_path = f"{name}.json"
    with open(local_path,"w") as json_file:
        json.dump(data,json_file,indent=4)
    local_2_remote(ssh_args,local_path,json_dir)
    os.remove(local_path)
    json_path = os.path.join(json_dir,f"{name}.json")
    message_content = {"file_path":json_path}
    message_body = json.dumps(message_content)
    msg = Message(topic)
    msg.set_tags("TagA")
    msg.set_body(message_body)
    _ = producer.send_sync(msg)
    producer.shutdown()
    return 


def core(remote_ip,zip_path,remote_dir):
    command = f'/data/Yang/environment/project_1/bin/python /data/Yang/project_1/SentinelL1cRasterServer.py {zip_path} {remote_dir}'     # 需要执行的cmd命令
    ssh_command = f'ssh root@{remote_ip} "{command}"'
    process = subprocess.run(
        ssh_command, 
        shell=True, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE, 
        text=True)
    if process.stderr:
        print("Error:", process.stderr)
        return False
    else:
        print("Output:", process.stdout)
        return True
    

def main():
    with open('./config.json',"r") as file:
        params = json.load(file)
    remote_ip = params['remote_host_ip'] 
    remote_dir = params['remote_dir'] 
    cargs = params["cargs"]
    ssh_args = params["ssh_args"]
    json_dir = params['json_dir']
    rediscon = params["rediscon"]
    pool = redis.ConnectionPool(**rediscon)
    redisr = redis.Redis(connection_pool=pool)
    while True:
        _,element = redisr.blpop('transfer_sender',0)
        zip_path = element.decode('utf-8')
        status = core(remote_ip,zip_path,remote_dir)
        if status: 
            send_data(ssh_args,cargs,json_dir,zip_path)
        else:
            redisr.lpush('raster_sender', zip_path)
    redisr.rpush('raster_sender', "None")  
    return


if __name__ == "__main__":
    main()